import Store from '@/store/index.js'
import Request from '@/api/request.js'
import * as WechatMiniApp from '@/api/wechat/wechat-miniapp.js'

function login(userName, password){
	return new Promise((resolve, reject) => {
		Request.request({
			isToken: false,
			url: 'login',
			method: "POST",
			data: {
				'username': userName,
				'password': password,
			},
		}).then(res=>{
			if(res.code == 200){
				if(res.token && res.token != ''){
					Store.setToken(res.token);
					resolve(res);
				} else {
					reject(res);
				}
			} else {
				reject(res);
			}
		}).catch(err =>{
			reject(err);
		})
	})
}

function getToken(userName, password){
	return new Promise((resolve, reject) => { 
		Request.request({
			isToken: false,
			url: 'login',
			method: "POST",
			data: {
				'username': userName,
				'password': password,
			},
		}).then(res=>{
			if(res.code == 200){
				if(res.token && res.token != ''){
					// Store.setToken(res.token);
					reject(res);
				} else {
					reject(res);
				}
			} else {
				reject(res);
			}
		}).catch(err =>{
			reject(err);
		})
	})
}

function getInfo(){
	return new Promise((resolve, reject) => {
		Request.request({
			isToken: true,
			url: 'getInfo'
		}).then(res=>{
			let user = res.user;
			if(res.user.type == 'people'){
				user.role = 'people';
				user.roleName = '受助人员';
			}else{
				user.id = user.userId;		//兼容原有用户表：原有用户表中没有id字段
				user.name = user.nickName;
				user.roles = res.roles;
				user.permissions = res.permissions;
			}
			console.log('登录成功')
			console.log(user)
			Store.setUser(user);
			Store.setAreaConfig(res.areaConfig);
			resolve(res.data);
		}).catch(err=>{
			reject(err);
		})
	})
}

function logout(){
	Store.clearToken();
	Store.clearUser();
	uni.navigateTo({
		url: '/pages/login'
	})
}

/**
 * 微信小程序自动登录
 * @param {Object} callback
 */
function wechatLogin(callback){
	let that = this;
	uni.login({
		provider: 'weixin', //使用微信登录
		success: function (loginRes) {
			if(loginRes.code && loginRes.code != ''){
				//使用 code 换取 openid&unionId 和 session_key 等信息
				WechatMiniApp.login(loginRes.code).then(session =>{
					// console.log(session);
					if(session.code == 200){
						console.log('登录成功');
						//缓存登录信息
						callback(session.data, true);
					} else {
						uni.showToast({
							title: session.msg
						})
					}
				})
			}
		}
	});
}

export default { login, getInfo, logout }
